package com.zx.idc.backend.gui.shiro;


import com.zx.idc.ds.tlog.service.ITLogActiveService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 *
 * @auth jinyuanf
 * @date 2019/4/28 15:55
 **/
public class RedisSessionDao extends EnterpriseCacheSessionDAO{

    private ITLogActiveService tlogActiveService;

    public void setTlogActiveService(ITLogActiveService tlogActiveService) {
        this.tlogActiveService = tlogActiveService;
    }

    private Cache cache() {
        Cache<Object, Object> cache = getCacheManager().getCache(this.getClass().getName());
        return cache;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        cache().put(sessionId.toString(), session);
        return sessionId;
    }

    /**
     * 通过sessionId获取session
     * @param sessionId
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = null;
        // 获取本次Request
        HttpServletRequest request = ServletKit.getRequest();
        if (request != null){
            String uri = request.getServletPath();
            // 过滤静态资源请求
            if (ServletKit.isStaticFile(uri)){
                return null;
            }
            // 在Request域中获取session
            session = (Session)request.getAttribute("session_"+sessionId);
        }
        if (session == null) {
            session = super.doReadSession(sessionId);
        }
        if (session == null) {
            session = (Session) cache().get(sessionId.toString());
        }
        return session;
    }

    @Override
    protected void doUpdate(Session session) {
        HttpServletRequest request = ServletKit.getRequest();
        if (request != null) {
            String uri = request.getServletPath();
            if (ServletKit.isStaticFile(uri)) {
                return;
            }
        }
        super.doUpdate(session);
        cache().put(session.getId().toString(), session);
    }

    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        cache().remove(session.getId().toString());
        tlogActiveService.deleteById(session.getId());
    }


}
